/******************************************************************************************
 *  @author: JobsGoo
 *  @ JobsGoo@gmail.com
 ******************************************************************************************/
#include <ice_log.h>
#include <ice_cream_config.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 ice_int32 main(ice_int32 argc, const char *argv[])
{
	ice_int8 buf[512];
	ice_super_block_t *super = NULL;
	ice_config_t *conf = NULL;
	int fd = 0;
	ice_log_open("ice_cream_create", LOG_NORMAL_E);
	if(argc < 2)
	{
		ICE_LOG_ERROR("Too less argv\n");
		printf("Too less argv\n");
		ice_log_close();
		return -1;
	}

	if(0 != access(argv[1], R_OK))
	{
		ICE_LOG_ERROR("%s is not exist\n", argv[1]);
		printf("%s is not exist\n", argv[1]);
		ice_log_close();
		return -1;
	}

	(void)snprintf(buf, 512, "%s/%s", argv[1], "super");
	(void)mkdir(buf, 0777);
	super = malloc(sizeof(ice_super_block_t));
	if(NULL == super)
	{
		printf("Error: no memory\n");
		ice_log_close();
		return -1;
	}

	memset(super, 0, sizeof(ice_super_block_t));
	super->magic = ICE_SUPER_MAGIC;
	super->version = 0;
	super->meta_size = META_SLICE_SIZE;
	(void)snprintf(buf, 512, "%s/%s/super.data", argv[1], "super");
	fd = open(buf, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
	if(-1 == fd)
	{
		ICE_LOG_ERROR("open %s failed\n", buf);
		printf("open %s failed\n", buf);
		free(super);
		ice_log_close();
	}

	ICE_LOG_NORMAL("write %s size:%u:%lld\n", buf, sizeof(ice_super_block_t), super->magic);
	(void)write(fd, super, sizeof(ice_super_block_t));
	free(super);
	super = NULL;
	close(fd);
	
	(void)snprintf(buf, 512, "%s/%s", argv[1], "meta");
	(void)mkdir(buf, 0777);

	(void)snprintf(buf, 512, "%s/%s", argv[1], "data");
	(void)mkdir(buf, 0777);	

	(void)snprintf(buf, 512, "%s/%s", argv[1], "recyc");
	(void)mkdir(buf, 0777);		

	conf = (ice_config_t*)malloc(sizeof(ice_config_t));
	if(NULL == conf)
	{
		ICE_LOG_ERROR("malloc failed for config\n");
		printf("write config failed\n");
		ice_log_close();
		return ;
	}

	memset(conf, 0, sizeof(ice_config_t));
	conf->magic = ICE_CONF_MAGIC;
	conf->version = 1;
	strcpy(conf->storage_path, argv[1]);
	fd = open("./ice_cream.db", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
	if(-1 == fd)
	{
		ICE_LOG_ERROR("open ice_cream.db\n");
		ice_log_close();
		return -1;
	}

	(void)write(fd, conf, sizeof(ice_config_t));
	close(fd);
	ice_log_close();
	return 0;
}


